
import { Component, director, _decorator } from 'cc';
import { tyqSDK } from '../Managers/TyqSDK';
import { GLoginState, GNetCmd, GNetConst } from '../Constans/Conf1';
import ServerCtr from '../Network/ServerCtr';
import TimeCtr from '../Network/TimeCtr';
import { WmSocket } from '../Network/Wmsocket';
const { ccclass, property } = _decorator;

@ccclass('CronCtr')
export default class CronCtr extends Component {

    private static _instance: CronCtr;

    public static getInstance(): CronCtr {
        if (!this._instance) {
            this._instance = new CronCtr();
        }
        return this._instance;
    }

    msgArr = [];
    msgArrIdx = 0;

    isPutEnable: boolean = false;
    testTimeDelta: number = 0;

    //保存队列，第一条和下一条按时间差150毫秒内的记录，统一一次性发送，发送成功后再发送下一批次
    //断线重连
    //本地存储登录返回的uid，区号
    //数据存储，key_uid_区号_time,按照time进行排序
    //服务端记录一个时间
    //切号
    // saverQueue:object[] = []; //{data:协议内容,time:TimeCtr.GetInstance().ServerTime}
    //
    // set SaverQueue(data){
    //     this.saverQueue.push({data:data, time:TimeCtr.GetInstance().ServerTime})
    // }

    init() {
        director.on(GNetCmd.Heartbeat.toString(), this.onHeartbeat)
        director.on(GNetCmd.SaveUserRecord.toString(), this.respSaveUserRecord, this)
        this.schedule(this.reqHeartBeat, 3);
        this.startHeartbeat()
    }

    startHeartbeat() {
        ///重连定时器
      
    }


    onHeartbeat(data: any) {
        // console.log("heartbeat ", data)
        if (data.status != GNetConst.ResSuccess) {
            // GD.GameState = GGameState.stop
            // mygame.pause()
            // TimeCtr.GetInstance().ServerTime = data.time
            //被抢登了
            if (ServerCtr.GetInstance().loginState == GLoginState.loginWithAccount) {
                ServerCtr.GetInstance().loginState = GLoginState.noYet;
            }
            TimeCtr.GetInstance().ReInit();
            // uiManager.instance.showDialog(Const.Dialogs.kick_prompt)
            // App.event(GameEvent.ShowFlyTips,{text:`<color=red>账号已在其他设备登录</c>`})//${i18n.t('txt.login_msg_out')}
            CronCtr.getInstance().isPutEnable = false;

            // let errMsg = `账号已在其他设备登录`;
            // let cheatLevel = localStorage.getItem("cheatLevel")
            // if(cheatLevel!=""){
            // 	cheatLevel = parseInt(cheatLevel)
            // 	if(cheatLevel==1){
            // 		errMsg = `<color=${Res.RedColor}>服务端检测到你正在使用非法外挂，如再发现直接封号</c>`;
            // 	}else if(cheatLevel==2){
            // 		errMsg = `<color=${Res.RedColor}>该区账号涉嫌作弊已被封禁，如再开挂所有区服全部封禁 </c>`;
            // 	}else if(cheatLevel>=3){
            // 		errMsg = `<color=${Res.RedColor}>该账号已封禁</c>`;
            // 	}
            // 	cc.sys.localStorage.removeItem("cheatLevel")
            // }
            // cc.game.restart();
        } else {
            TimeCtr.GetInstance().UpdateServerTimeByHeartbeat(data.time * 1000);
            WmSocket.getInstance().lastHeartbeatTime = TimeCtr.GetInstance().ServerTime
        }
        // else{
        // 	//检查版本号是否和服务端匹配
        // 	if (data.version.includes('@'+this.center.Version)==false){
        // 		this.ui.CloseAllPanel();
        // 		this.ui.ShowPanel('LoadPanel');
        // 		//弹窗提示当前版本号不对
        // 		App.event(GameEvent.ShowFlyTips,{text:`<color=red>发现新版本，请先更新!</c>`})//${i18n.t('txt.login_msg_version')}
        // 		GlParam.isEnterGame = false;
        // 	}
        // }
    }

    reqHeartBeat() {
        // console.log("-----心跳-----", WmSocket.getInstance().isConnected(), ServerCtr.GetInstance().loginState);

        if (WmSocket.getInstance().isConnected() == false) {
            // uiManager.instance.showDialog(Const.Dialogs.net_prompt, )
            // Notifications.emit(GDef.wdEvent.showTip, {msg:"网络连接异常"})
         
        } else {
            if (ServerCtr.GetInstance().loginState == GLoginState.loginFail) {
                //重连后登录
                ServerCtr.GetInstance().wxLoginBegin();
            } else {
                this.heartbeatCheck()
            }
        }
    }


    respSaveUserRecord(data: any) {

        if (data.status == GNetConst.ResFail) {
            console.error("发现作弊1----", data, data.cheatLevel, data.hasOwnProperty("cheatLevel"))
            // let cheatLevel = data.cheatLevel
            // if(cheatLevel!==undefined){
            //     // cc.log("cheatLevel2--------!!!!---", cheatLevel)
            //     localStorage.setItem("cheatLevel", cheatLevel+"")
            //     //直接发送一个心跳利用心跳到登录页面
            //     let data = {
            //         "cmd": GNetCmd.Heartbeat,
            //         "lang": "zh",
            //         "token": ServerCtr.GetInstance().token,//GameStorage.getString("loginToken"),
            //     }
            //     WmSocket.getInstance().send({"data":data});
            // }
            // uiManager.instance.showDialog(Const.Dialogs.kick_prompt)
            // GameStorage.setString("cheatLevel", data.cheatLevel)
        }
        // if(data["isEnd"]==false){
        //     this.sendMultiMsg(data["idx"]+1)
        // }
    }

    // cloudSave(obj){
    //     // 进入游戏每隔5分钟存储一次
    //     obj.schedule(()=>{
    //         if(!GlParam.isEnterGame){
    //             return;
    //         }
    //         this.cloudSaveManual()
    //         // if(WmSocket.getInstance().isConnected()){
    //         //     let data = {
    //         //         "cmd": GNetCmd.SaveUserRecord,
    //         //         "lang": "zh",
    //         //         "token": GameStorage.getString("loginToken"),
    //         //         // "jsonData": JSON.stringify(GameStorage.getAll()),
    //         //         "jsonData": JSON.stringify(GameStorage.getAll()),
    //         //     }
    //         //     cc.log("长度测试",JSON.stringify(GameStorage.getAll()).length)
    //         //     WmSocket.getInstance().send({"data":data});
    //         // }

    //     }, 300);
    // }

    sendMultiMsg(i: number) {
        // for(let i=0; i<strArr.length; i++){
        //
        // }

        let data = {
            // "cmd": GNetCmd.SaveUserRecord,
            "cmd": GNetCmd.SaveUserRecord,
            "lang": "zh",
            "type": "slice",
            "token": ServerCtr.GetInstance().token,//GameStorage.getString("loginToken"),
            // "jsonData":JSON.stringify(GameStorage.getAll()),
            "jsonData": this.msgArr[i],
            "isEnd": i == this.msgArr.length - 1,
            "isStart": i == 0,
            "idx": i
        }
        if (!data.jsonData || data.jsonData == "" || data.jsonData == "{}") {
            return
        }
        // cc.log("分段存储", data)
        WmSocket.getInstance().send({ "data": data });
    }

    //保存数据到云端
    saveDataToCloud(key: string, val: any) {
        if (ServerCtr.GetInstance().loginState != GLoginState.loginWithAccount) {
            return;
        }
        // cc.log("上传数据时间标记---------", new Date().getTime(),  new Date().getTime()-this.testTimeDelta )
        this.testTimeDelta = new Date().getTime()
        if (WmSocket.getInstance().isConnected()) {
            let data = {
                "cmd": GNetCmd.SaveUserRecord,
                "lang": "zh",
                "type": "single",
                "token": ServerCtr.GetInstance().token,//GameStorage.getString("loginToken"),
                "version": ServerCtr.GetInstance().dataVersion,
                // "jsonData":JSON.stringify(GameStorage.getAll()),
                // "jsonData":JSON.stringify(GameStorage.getAll(isFirst)),
                "key": key,
                "val": String(val),
                "dml": "add upd"
            }
            // cc.log("长度测试", JSON.stringify(GameStorage.getAll(isFirst)).length)
            WmSocket.getInstance().send({ "data": data });
        }
    }

    uploadAllRecord(jsonData: any) {
        if (ServerCtr.GetInstance().loginState != GLoginState.loginWithAccount) {
            return;
        }
        let data = {
            // "cmd": GNetCmd.SaveUserRecord,
            "cmd": GNetCmd.SaveUserRecordAll,
            "lang": "zh",
            "type": "single",
            "token": ServerCtr.GetInstance().token,//GameStorage.getString("loginToken"),
            // "jsonData":JSON.stringify(GameStorage.getAll()),
            "version": ServerCtr.GetInstance().dataVersion,
            "allData": JSON.stringify(jsonData),
        }
        // if (!data.jsonData || data.jsonData == "" || data.jsonData == "{}") {
        //     return
        // }
        // cc.log("长度测试", JSON.stringify(GameStorage.getAll(isFirst)).length)
        console.warn("发送数据到云端---", data)
        WmSocket.getInstance().send({ "data": data });
    }

    // UploadEmptyRecord(){
    //     if (!ServerCtr.GetInstance().isLogin) {
    //         return;
    //     }
    //     let data = {
    //         // "cmd": GNetCmd.SaveUserRecord,
    //         "cmd": GNetCmd.SaveUserRecordAll,
    //         "lang": "zh",
    //         "type": "single",
    //         "token": ServerCtr.GetInstance().token,//GameStorage.getString("loginToken"),
    //         // "jsonData":JSON.stringify(GameStorage.getAll()),
    //         "allData":JSON.stringify({}),
    //     }
    //     // if (!data.jsonData || data.jsonData == "" || data.jsonData == "{}") {
    //     //     return
    //     // }
    //     // cc.log("长度测试", JSON.stringify(GameStorage.getAll(isFirst)).length)
    //     WmSocket.getInstance().send({"data":data});
    // }


    // cloudDeleteManual(key:string){
    //     // if (!this.isPutEnable) {
    //     //     return;
    //     // }
    //     if (!ServerCtr.GetInstance().isLogin) {
    //         return;
    //     }
    //     if(WmSocket.getInstance().isConnected()){
    //         let data = {
    //             // "cmd": GNetCmd.SaveUserRecord,
    //             "cmd": GNetCmd.SaveUserRecord,
    //             "lang": "zh",
    //             "type": "single",
    //             "token": ServerCtr.GetInstance().token,//GameStorage.getString("loginToken"),
    //             "key":key,
    //             "val":"",
    //             "dml":"del"
    //         }
    //         Public.warn("del--------------")
    //         WmSocket.getInstance().send({"data":data});
    //     }
    // }

    heartbeatCheck() {
        let data = {
            "cmd": GNetCmd.Heartbeat,
            "lang": "zh",
            "token": ServerCtr.GetInstance().token,//GameStorage.getString("loginToken"),
        }
        WmSocket.getInstance().send({ "data": data });
    }

}
